<?php
namespace app\admin\controller;
use app\service\billService;
use invoice\Api;
use think\facade\Db;
use think\facade\View;

class Parking extends Common{
    public function gateList(){
        $com = $this->pidTokenId();
        if($com["usertype"]=="2"){
            return "无权访问";
        }
        $data = request()->get();
        if (!empty($data)){
//            if(!empty($data['property_name'])){
//                $where['name'] = array("like","%".$data['property_name']."%");//账单编号
//            }
        }
        //$where['a.property_id'] = array('in',$com['property_id']);
        $where[] =['a.property_id','in',$com['property_id']];
        $where = array_filter($where);
        $prolist =Db::name('property_parking_gate')
                        ->alias("a")
                        ->join("property b","a.property_id=b.id")
                        ->join("community c","a.community_id=c.community_id","left")
                        ->where($where)
                        ->field("a.*,b.name,c.community_name as c_name")
                        ->order('a.id asc')
                        ->paginate(20);
        $number = Db::name('property_parking_gate')->alias("a")->where($where)->count();
        View::assign('number',$number);

        View::assign('list',$prolist);
        View::assign('prolist',$prolist);
        foreach ($data as $k => $v) {
            View::assign($k, $v);
        }
        return View::fetch("gate_list");
    }
    
    
    public function gateAdd(){
         //根据当前账号查询物业信息
        $com = $this->pidTokenId();
        $where['id'] = array('in',$com['property_id']);
        $propertylist =Db::name('property')->where($where)->order('id desc')->select()->toArray();
        View::assign('propertylist',$propertylist);
        if(request()->isPost()){
            //获取表单数据
            $data = request()->post();
          
            //将数据插入数据库
            $result = Db::name('property_parking_gate')->insert($data);
            //判断数据是否插入成功
            if($result){
                $this->success('添加成功',url('gateList'));
            }else{
                $this->error('添加失败',url('gateAdd'));
            }
        }else{
            return View::fetch('gate_add');
        }
    }
    
    public function gateEdit(){
         //根据当前账号查询物业信息
        $com = $this->pidTokenId();
        $where['id'] = array('in',$com['property_id']);
        $propertylist =Db::name('property')->where($where)->order('id desc')->select()->toArray();
        View::assign('propertylist',$propertylist);
        if(request()->isPost()){
            //获取表单数据
            $data = request()->post();
          
            //将数据插入数据库
            $result = Db::name('property_parking_gate')->update($data);
            //判断数据是否插入成功
            if($result){
                $this->success('修改成功',url('gateList'));
            }else{
                $this->error('修改失败',url('gateList'));
            }
        }else{
            $id=request()->get("id");
            $info=Db::name('property_parking_gate')->where("id",$id)->find();
            View::assign("info",$info);

            $communityList=Db::table("community")->where("community_id","in",$com['community_id'])->select()->toArray();
            View::assign("communityList",$communityList);
            return View::fetch('gate_edit');
        }
    }
    
    public function billParkList(){
        $com = $this->pidTokenId();
        if($com["usertype"]=="2"){
            return "无权访问";
        }
        $data = request()->get();
        $where['property_id'] = array('in',$com['property_id']);
        //var_dump($com["community_id"]);
        //$gateid=Db::name('property_parking_gate')->column('id');
        $gatelist =Db::name('property_parking_gate')->where($where)->select()->toArray();
        View::assign("gatelist",$gatelist);
        if (!empty($data)){
            if(!empty($data['community_name'])){
                $where['community_name'] = array("like","%".$data['community_name']."%");
            }else{
                $where['community_name'] = "";
            }
            if(!empty($data['invoice_type'])){
                $where['invoice_type'] = $data['invoice_type'];
            }else{
                $where['invoice_type'] = "";
            }
            if(!empty($data['gateid'])){
                $where['gateid'] = $data['gateid'];
            }else{
                $where['gateid'] = "";
            }
            
            
            if((!empty($data['gmt_payment_start']))&&(empty($data['gmt_payment_end']))){
				$where['pay_time']=array('>=',strtotime($data['gmt_payment_start']));
                $gmt_payment_start = $data['gmt_payment_start'];
                View::assign('gmt_payment_start',$gmt_payment_start);
            }
			if((!empty($data['gmt_payment_end']))&&(empty($data['gmt_payment_start']))){
				$where['pay_time']=array('<=',strtotime($data['gmt_payment_end']));
                $gmt_payment_end = $data['gmt_payment_end'];
                View::assign('gmt_payment_end',$gmt_payment_end);
            }
			if((!empty($data['gmt_payment_start']))&&(!empty($data['gmt_payment_end']))){
				$where['pay_time']=array(array('>=',strtotime($data['gmt_payment_start'])),array('<=',strtotime($data['gmt_payment_end'])));
                $gmt_payment_start = $data['gmt_payment_start'];
				$gmt_payment_end = $data['gmt_payment_end'];
                View::assign('gmt_payment_start',$gmt_payment_start);
				View::assign('gmt_payment_end',$gmt_payment_end);
            }
        }
        
        $where = array_filter($where);
        $export = $where;
        $export = json_encode($export);
        $export = str_replace("\"","|",$export);
        View::assign("export",$export);
        $prolist =Db::name('billparkorder')->where($where)->order('id desc')->paginate(20);
        $number = Db::name('billparkorder')->where($where)->count();
        $money["ali"]=Db::name('billparkorder')->where($where)->where("pay_type","1")->sum("pay_money");
        $money["wx"]=Db::name('billparkorder')->where($where)->where("pay_type","2")->sum("pay_money");
        View::assign("money",$money);
        View::assign('number',$number);
        if(!empty($number)){
            foreach($prolist as $lis){
                $id = $lis['property_id'];
                $proname = Db::name('property')->where('id',$id)->find();;
                $lis['property_id'] = $proname['name'];
                $list[] = $lis;
                View::assign('list',$list);
            }
        }else{
            View::assign('list',$prolist);
        }
        View::assign('prolist',$prolist);
        foreach ($data as $k => $v) {
            View::assign($k, $v);
        }
        return View::fetch("bill_park_list");
    }
    
    //批量导出
    public function billOrderExport(){
        //获取账单数据
        $id = request()->param('id');
        $export = request()->param('export');
        //Log::write(request()->param(),"账单导出参数");
        $export = str_replace("|","\"",$export);
        if(!empty($id)){
            $id = explode(',',request()->param('id'));
            $billList = Db::name('billparkorder')->where('id','in',$data)->select()->toArray();
            if (count($billList) != count($id)) {
                return json(['error' => '账单信息不完整']);
            }
        }else{
            //查询小区信息
            $com = $this->pidTokenId();
            $community_id = $com['community_id'];            
            $where = json_decode($export,true);
            
            $billList = Db::name('billparkorder')->where($where)->order('id desc')->select()->toArray();
            if(empty($billList)){
                return json(['error' => '没有账单数据']);
            }
        }
        //var_dump($billList);die;
        //设置表头
        //引入PHPExcel类
        vendor('PHPExcel.PHPExcel.Reader.Excel2007');
        $objPHPExcel = new \PHPExcel();
        //设置表头
        $objPHPExcel->setActiveSheetIndex(0)
        ->setCellValue('A1', '小区名称')
        ->setCellValue('B1', '岗亭')
        ->setCellValue('C1', '金额')
        ->setCellValue('D1', '支付方式')
        ->setCellValue('E1', '付款时间');

        $i=2;  //定义一个i变量，目的是在循环输出数据是控制行数
        $count = count($billList);  //计算有多少条数据
        for ($i = 2; $i <= $count+1; $i++) {
            $objPHPExcel->getActiveSheet()->setCellValue('A' . $i, $billList[$i-2]["community_name"]);
            
            $objPHPExcel->getActiveSheet()->setCellValue('B' . $i, $billList[$i-2]["gateName"]);
            $objPHPExcel->getActiveSheet()->setCellValue('C' . $i, $billList[$i-2]["pay_money"]);
            
            $pay_type = '支付宝';
            if($billList[$i-2]["pay_type"] == '2'){
                $pay_type="微信";
            }
            $pay_time=date("Y-m-d H:i:s",$billList[$i-2]["pay_time"]);
            $objPHPExcel->getActiveSheet()->setCellValue('D' . $i, $pay_type);
            $objPHPExcel->getActiveSheet()->setCellValue('E' . $i, $pay_time);
            
        }
        $objPHPExcel->getActiveSheet()->setTitle('停车收款信息');      //设置sheet的名称
        $objPHPExcel->setActiveSheetIndex(0);                   //设置sheet的起始位置
        header('Content-Disposition: attachment;filename="停车收款.xls"');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        $PHPWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel,"Excel2007"); //通过PHPExcel_IOFactory的写函数将上面数据写出来
        $PHPWriter->save("php://output"); //表示在$path路径下面生成demo.xlsx文件
    }
    public function orderrefund(){
		if(request()->isPost()){
			$data=request()->post();
			$orderinfo=Db::table("bill")->where("id",$data["id"])->find();
			$orderinfo["refund_money"]=$data["refund_money"];
			$orderinfo["out_order_no"]="";
			$api=new lifeapiService();
			$orderinfo["token"] = (new roominfoService())->communityToken($orderinfo['community_id']);
			$result=$api->refund(json_encode($orderinfo));
			echo "<pre>";
			var_dump($result);
			if($result->code=="10000"){
			
				Db::table("bill")->where("id",$data["id"])->update(["status"=>"REFUND"]);
				unset($orderinfo["token"]);
				//$orderinfo["refund_operator"]=session("name");
				//$res=Db::table("car_order_refund")->insert($orderinfo);
				return "退款成功";
			}else{
				return "退款失败";
			}
			
		}else{
			$orderid=request()->get("id");
			$orderinfo=Db::table("bill")->where("id",$orderid)->find();
			View::assign("orderinfo",$orderinfo);
			return View::fetch("order_refund");
		}
		
	}
	
	
	
	//开票接口
    public function invoice(){
        //查询是否有access_token
        //判断是否存在该数据
        $id=request()->get("id");    
        $billinfo = Db::table("billparkorder")->where("id",$id)->find();
        if (empty($billinfo)) {
            return json(['error' => '账单不存在']);
        }
        
        $info=$billinfo;
        if($billinfo['invoice_type'] == '1'){
            return json(['error' => '不能重复开票']);
        }
        $bill_entry_amount=$info['pay_money'];
        
        $taxrate = 0.06;
        if(empty($taxrate)){
        	return "请添加该小区的费用类型";
        }
        
        $tax = $info['order_money']*$taxrate;
        $bill_entry_amount= $info['order_money'];
        $info['cost_type']="车位费";
        //$inf['cost_type']="物业费";
        $invoiceDetail = "{'goodsName':'{$info['cost_type']}','specType':'','unit':'期','num':'1','price':'{$bill_entry_amount}','withTaxFlag':'1','taxRate':'{$taxrate}','tax':'{$tax}'}";
        
        $remark = '支付宝支付';
        if($info['pay_type']=="2"){
            $remark="微信支付";
        }
       
        
       
       
       
        $propertyinfo = (new billService())->propertyInfo($info['property_id']);
        $serviceinfo = (new billService())->serviceInfo($propertyinfo['service_id']);
        // dump($propertyinfo);
        
        if(empty($serviceinfo["fp_app_key"])){
            return "请先配置发票信息";
        }
        
        //判断access_token是否到期
        $second = strtotime(date('Y-m-d H:i:s',time()))-strtotime($serviceinfo['fp_expires_in']);
        if($second <86400){
            //未过期
            $access_token = $serviceinfo['fp_access_token'];
        }else{
            //过期从新获取
            $access_token = $this->accessToken($serviceinfo['fp_app_key'],$serviceinfo['fp_app_secret']);
        }
        
        $appKey = $serviceinfo["fp_app_key"];
     	$appSecret = $serviceinfo["fp_app_secret"];
    	$token = $access_token;// please store the token and refresh it before expired
    	$taxnum = $serviceinfo["fp_saler_tax_num"];
        
    	$url = "https://sdk.nuonuo.com/open/v1/services"; // change to online domain
    	$method = "nuonuo.electronInvoice.requestBilling"; // change to your method
		$senid = uniqid(); // generate your meaningful senid
		
		$invoiceDate = date('Y-m-d H:i:s',time());
        $orderNo = time().rand(100000,999999);
        $timestmp = time(); 
        $buyerName=$info['community_name'];
        $buyerPhone="";
        //$buyerPhone="188561510";
        $fp_saler_tax_num=$serviceinfo['fp_saler_tax_num'];
        $salerAddress=$serviceinfo['address'];
        $salerTel=$serviceinfo['phone'];
        $salerAddress=$serviceinfo['address'];
        $salerAccount=$serviceinfo['fp_saler_account'];
        $emt="";
        
        //var_dump($content);
        $body = "{
        \"order\": {
            \"buyerName\": \"$buyerName\",
            \"orderNo\": \"$orderNo\",
            \"invoiceDate\": \"$invoiceDate\",
            \"clerk\": \"\",
            \"salerTaxNum\": \"$fp_saler_tax_num\",
            \"salerTel\": \"$salerTel\",
            \"salerAddress\": \"$salerAddress\",
            \"salerAccount\": \"$salerAccount\",
            \"invoiceType\": \"1\",
            \"pushMode\": \"1\",
            \"buyerPhone\": \"$buyerPhone\",
            \"remark\": \"$remark\",
            \"invoiceDetail\": [$invoiceDetail],
            \"callBackUrl\": \"http://www.jfzhiwen.com/admin/invoice/callback/\"
            }
        }";
        
        //var_dump($body);//die;
       
	
        $result = Api::sendPostSyncRequest($url, $senid, $appKey, $appSecret, $token, $taxnum, $method, $body);
        //var_dump($result);
		$result = json_decode($result, true);

        if($result['code'] == 'E0000'){
            $invoiceSerialNum = $result['result']['invoiceSerialNum'];
            
            $data['id'] = $info['id'];
            $data['invoice_serial_num'] = $invoiceSerialNum;
            $data['invoice_type'] = 1;
            $billinvoiceSerialNum =Db::table("billparkorder")->update($data);
            
        }else{
            return json(['error' => $result['describe']]);
        }
        return json(['success' => '开票成功']);
        $this->success("付款成功");
        
    }
    
    //发票冲红
    public function Cancellation(){
        //判断是否存在该数据
        $id = request()->param('id');
	    //var_dump($id);die;
        $billinfo = Db::table("billparkorder")->where("id",$id)->find();
        
        if(empty($billinfo)){
            return '账单信息错误';
        }
        //根据发票号查询开票账单
        
        if($billinfo["invoice_type"]!="1"){
            return json(['error' => '已冲红或未开票']);            
        }
        
        $info=$billinfo;
        //根据费用类型查询税率
        $taxrate = 0.06;
        //$taxrate = (new billService())->taxRate($inf['cost_type']);
        $tax = $info['pay_money']*$taxrate;
        $info['cost_type']="车位费";
        $invoiceDetail = "{'goodsName':'{$info['cost_type']}','specType':'','unit':'期','num':'-1','price':'{$info['pay_money']}','withTaxFlag':'1','taxRate':'{$taxrate}','tax':'-{$tax}'}";
        $remark = '支付宝支付';
        if($info['pay_type']=="2"){
            $remark="微信支付";
        }
        
        
       
        
        $propertyinfo = (new billService())->propertyInfo($billinfo['property_id']);
        $serviceinfo = (new billService())->serviceInfo($propertyinfo['service_id']);
        //判断access_token是否到期
        $second = strtotime(date('Y-m-d H:i:s',time()))-strtotime($serviceinfo['fp_expires_in']);
        if($second < 86400){
            //未过期
            $access_token = $serviceinfo['fp_access_token'];
        }else{
            //过期从新获取
            $access_token = $this->accessToken($serviceinfo['fp_app_key'],$serviceinfo['fp_app_secret']);
        }
        $invoiceDate = date('Y-m-d H:i:s',time());
        $orderNo = time().rand(100000,999999);
        $timestmp = time();
        
        
        $appKey = $serviceinfo["fp_app_key"];
     	$appSecret = $serviceinfo["fp_app_secret"];
    	$token = $access_token;// please store the token and refresh it before expired
    	$taxnum = $serviceinfo["fp_saler_tax_num"];
        $url = "https://sdk.nuonuo.com/open/v1/services"; // change to online domain
        
        $method2 = "nuonuo.electronInvoice.CheckEInvoice"; // change to your method
		$senid2 = uniqid(); // generate your meaningful senid
		$body2 = json_encode(
			array(
				"invoiceSerialNum" => array($billinfo['invoice_serial_num'])
			)
		);
        
		$result2 = Api::sendPostSyncRequest($url, $senid2, $appKey, $appSecret, $token, $taxnum, $method2, $body2);
        $result2 = json_decode($result2, true);
         
        if($result2['code'] != 'E0000'){
           return json(['error' => $result2['describe']]);
        }
        //var_dump($result2);die;
        $invoiceCode = $result2['result'][0]['invoiceCode'];
        $invoiceNum = $result2['result'][0]['invoiceNum'];
        
    	
    	$method = "nuonuo.electronInvoice.requestBilling"; // change to your method
		$senid = uniqid(); // generate your meaningful senid
		
		$invoiceDate = date('Y-m-d H:i:s',time());
        $orderNo = time().rand(100000,999999);
        $timestmp = time(); 
        $buyerName=$info['community_name'];
        $buyerPhone='';
        //$buyerPhone="188561510";
        $fp_saler_tax_num=$serviceinfo['fp_saler_tax_num'];
        $salerAddress=$serviceinfo['address'];
        $salerTel=$serviceinfo['phone'];
        $salerAddress=$serviceinfo['address'];
        $salerAccount=$serviceinfo['fp_saler_account'];
        $body = "{
        \"order\": {
            \"buyerName\": \"$buyerName\",
            \"orderNo\": \"$orderNo\",
            \"invoiceDate\": \"$invoiceDate\",
            \"clerk\": \"\",
            \"salerTaxNum\": \"$fp_saler_tax_num\",
            \"salerTel\": \"$salerTel\",
            \"salerAddress\": \"$salerAddress\",
            \"salerAccount\": \"$salerAccount\",
            \"invoiceType\": \"2\",
            \"invoiceCode\": \"$invoiceCode\",
            \"invoiceNum\": \"$invoiceNum\",
            \"pushMode\": \"1\",
            \"buyerPhone\": \"$buyerPhone\",
            \"invoiceDetail\": [$invoiceDetail],
            \"callBackUrl\": \"http://www.jfzhiwen.com/admin/invoice/callback/\"
            }
        }";
       
           
        
        $result = Api::sendPostSyncRequest($url, $senid, $appKey, $appSecret, $token, $taxnum, $method, $body);
        // var_dump($result);
		
        $result = json_decode($result, true);
        if($result['code'] == 'E0000'){
            $invoiceSerialNum = $result['result']['invoiceSerialNum'];
            
            $data['id'] = $inf['id'];
            $data['invoice_serial_num'] = $invoiceSerialNum;
            $data['invoice_type'] = 2;
            $billinvoiceSerialNum =Db::table("billparkorder")->update($data);
            return json(['info' => '冲红成功']);       
            
        }else{
            return json(['error' => $result['describe']]);
        }
        
    }
    
    public function CheckEInvoice() 
	{
	    $id = request()->param('id');
	    //var_dump($id);die;
        $billinfo = Db::table("billparkorder")->where("id",$id)->find();
        
       
        
        $propertyinfo = (new billService())->propertyInfo($billinfo['property_id']);
        
        $serviceinfo = (new billService())->serviceInfo($propertyinfo['service_id']);
        
        //判断access_token是否到期
        $second = strtotime(date('Y-m-d H:i:s',time()))-strtotime($serviceinfo['fp_expires_in']);
        if($second < 86400){
            //未过期
            $access_token = $serviceinfo['fp_access_token'];
        }else{
            //过期从新获取
            $access_token = $this->accessToken($serviceinfo['fp_app_key'],$serviceinfo['fp_app_secret']);
            //return $access_token;
        }
        //var_dump($access_token);die;
        $timestmp = time();
       
		$appKey = $serviceinfo["fp_app_key"];
     	$appSecret = $serviceinfo["fp_app_secret"];
    	$token = $access_token;// please store the token and refresh it before expired
    	$taxnum = $serviceinfo["fp_saler_tax_num"];
    
    	$url = "https://sdk.nuonuo.com/open/v1/services"; // change to online domain
    	$method = "nuonuo.electronInvoice.CheckEInvoice"; // change to your method
		$senid = uniqid(); // generate your meaningful senid
		$body = json_encode(
			array(
				"invoiceSerialNum" => array($billinfo['invoice_serial_num'])
			)
		);
        
		$result = Api::sendPostSyncRequest($url, $senid, $appKey, $appSecret, $token, $taxnum, $method, $body);
	
	
		$result = json_decode($result, true);
		//	echo "<pre>";
        //var_dump($result);die;
        if($result['code'] == 'E0000'){
            return $this->redirect($result['result'][0]['invoiceFileUrl']);
        }else{
            return json(['error' => $result['describe']]);
        }
		return $res;
	}
    
    //当access_token超时时，获取access_token
    public function accessToken($client_id,$client_secret){
        $res = Api::getMerchantToken($client_id, $client_secret);
		$tmpInfo = json_decode($res);

        
        if(property_exists($tmpInfo,'error')){
            //var_dump($tmpInfo);die;
            //return $tmpInfo;
            $this->error($tmpInfo->error.',access_token获取失败');
        }
        $data['fp_access_token'] = $tmpInfo->access_token;//获取access_token
        $data['fp_expires_in'] = date('Y-m-d H:i:s',time());
        $data['id'] = (new billService())->serviceFpAppKey($client_id);
        // 存储access_token
        $result = (new billService())->serviceUpdate($data);
        return $data['fp_access_token'];
        // $tmpInfo = '{"access_token":"10ffd45208fb4464aa6fee00vthjozss","expires_in":86400}';
        
    }
	public function getMerchantToken() {
		$appKey = "your.appKey";
		$appSecret = "your.appSecret";
		$res = Api::getMerchantToken($appKey, $appSecret);
		return $res;
	}

	public function getISVToken() {
		$appKey = "your.appKey";
		$appSecret = "your.appSecret";
		$code = "your.code";
		$taxnum = "your.merchant.taxnum";
		$redirectUri = "your.redirectUri";
		$res = Api::getISVToken($appKey, $appSecret, $code, $taxnum, $redirectUri);
		return $res;
	}

	public function refreshISVToken() {
		$refreshToken = "your.token";
		$appSecret = "your.appSecret";
		$userId = "your.userId";
		$res = Api::refreshISVToken($refreshToken, $userId, $appSecret);
		return $res;
	}
	
	public function test(){
	    $appKey = "uXig5unv";
		$appSecret = "B69D206D6E564A6E";
		$code = request()->get("code");
		$taxnum = "91330110352478198K";
		$redirectUri = "https://www.wuye.zfbzhsq.com/admin/invoice/test";
		$res = Api::getISVToken($appKey, $appSecret, $code, $taxnum, $redirectUri);
		var_dump($res);
		return $res;
	}
}